<template>
  <div class="m-2 mr-0 overflow-hidden">
    <BasicTree title="字典分类" search :clickRowToExpand="false" :actionList="actionList" :treeData="treeData" :fieldNames="fieldNames" @select="handleSelect">
      <template #headerTitle>
        <a-button type="primary" size="small" @click="handleCreate">添加分类</a-button>
      </template>
    </BasicTree>
    <DictModal @register="registerModal" @success="fetch"/>
  </div>
</template>
<script lang="ts" name="DictTree" setup>
import {h, onMounted, ref} from 'vue';
import {BasicTree, TreeActionItem} from '@/components/tree/index';
import DictModal from './DictModal.vue';
import {getDictTreeList, Api} from '@/views/sys/dict/data/dict.api';
import {useModal} from "@/components/modal";
import {FormOutlined, DeleteOutlined} from '@ant-design/icons-vue'
import {Popconfirm} from 'ant-design-vue';
import {request} from '@pkg/request/src';

const [registerModal, {openModal}] = useModal();

const emit = defineEmits(['register', 'select']);
const treeData = ref<any[]>([]);
const fieldNames = {title: "dicTitle", key: "dictId"}

async function fetch() {
  treeData.value = await getDictTreeList({});
}

/**
 * 节点选择事件
 * @param keys
 */
function handleSelect(keys) {
  emit('select', keys[0]);
}

/**
 * 打开新增弹框
 */
function handleCreate() {
  openModal(true, {
    isUpdate: false
  });
}

/**
 * tree操作按钮
 * @param node
 */
const actionList: TreeActionItem[] = [
  {
    render: (node) => {
      return h(FormOutlined, {
        class: 'ml-2',
        onClick: () => {
          openModal(true, {
            isUpdate: true,
            record: {
              dictId: node.dictId,
              dicType: node.dicType,
              dicTitle: node.dicTitle.el.innerText
            }
          });
        },
      })
    },
  },
  {
    render: (node) => {
      return h(Popconfirm, {
        title: "确定删除吗吗？",
        onConfirm: () => {
          let params = {
            dictId: node.dictId
          }
          request.post({url: Api.remove, params}).then(() => {
            fetch();
          });
        }
      }, [h(DeleteOutlined, {
        class: 'ml-2'
      })])
    },
  },
]

onMounted(() => {
  fetch();
});
</script>
